<?php
declare (strict_types = 1);

namespace app\adminapi\model\system\auth;

use adminmatrix\server\app\model\BaseModel;
use think\Model;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

/**
 * @mixin \think\Model
 */
class AdminUser extends BaseModel
{
    protected array $hidden = [
        'password' , 'salt'
    ];

    protected array $type = [
        'status'    =>  'bool'
    ];

    #-------------------------------------------------------------------
    # 模型事件
    #-------------------------------------------------------------------

    # 查询后
    public static function onAfterRead(Model $model): void
    {
        $model->role_name = $model->name('AdminRole' ) -> whereIn('id' , $model->role->column('role_id')) -> column('name');
//        parent::onAfterRead($model); // TODO: Change the autogenerated stub
    }

    public static function onAfterDelete(Model $model) : void
    {
        $model->info()->delete();
    }


    #-------------------------------------------------------------------
    # 关联表
    #-------------------------------------------------------------------

    # 关联角色
    public function role() : HasMany
    {
        return $this->hasMany(AdminUserRole::class ,'user_id');
    }

    # 关联用户详情
    public function info() : HasOne
    {
        return $this->hasOne(AdminInfo::class , 'admin_id');
    }

    #-------------------------------------------------------------------
    # set Attr
    #-------------------------------------------------------------------

    # 设置ip 转换
    public function setLastLoginIpAttr($ip) : int |string
    {
        if (empty($ip)) return '';
        return  ip2long($ip);
    }
}
